package cn.ddm.hrm.service.impl;


import cn.ddm.hrm.ai.IAIContentAuditService;
import cn.ddm.hrm.client.CourseDocClient;
import cn.ddm.hrm.config.RabbitMQConfig;
import cn.ddm.hrm.doc.CourseDoc;
import cn.ddm.hrm.domain.*;
import cn.ddm.hrm.dto.CourseDto;
import cn.ddm.hrm.enums.CourseGrade;
import cn.ddm.hrm.exception.ErrorCode;
import cn.ddm.hrm.exception.ValidUtils;
import cn.ddm.hrm.holder.UserContextInfoHolder;
import cn.ddm.hrm.mapper.*;
import cn.ddm.hrm.query.CourseDocQuery;
import cn.ddm.hrm.query.CourseQuery;
import cn.ddm.hrm.service.ICourseService;
import cn.ddm.hrm.util.AjaxResult;
import cn.ddm.hrm.util.PageList;
import cn.ddm.hrm.vo.UserContextInfo;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaosang
 * @since 2022-01-08
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private CourseMapper courseMapper;
    @Autowired
    private CourseMarketMapper courseMarketMapper;
    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private IAIContentAuditService aiContentAuditService;

    @Autowired
    private CourseAuditLogMapper courseAuditLogMapper;

    @Autowired
    private CourseOnlineLogMapper courseOnlineLogMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    @Autowired
    private CourseDocClient courseDocClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Override
    public PageList<Course> selectPageList(CourseQuery query) {
        Page page = new Page(query.getPage(),query.getRows());
        List<Course> datas = courseMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),datas);
    }

    @Override
    @Transactional
    public void updateById(CourseDto courseDto) {
        Course course = courseDto.getCourse();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        //  进行相关校验
        // 参数校验

        CourseGrade grade = CourseGrade.getGrade(course.getGradeId().intValue());
        ValidUtils.assertNotNull(grade, ErrorCode.CODE_400_COURSE_GRADE_ILLEGAL);

        String content = course.getName()+" "+ course.getForUser()+" "+ courseDetail.getIntro()+" "+ courseDetail.getDescription();
        AjaxResult ajaxResult = aiContentAuditService.audit(content, null, null);
        int status = ajaxResult.isSuccess()?1:-1;
        //2 正在操作
        //添加课程
        course.setStatus(status);
        courseMapper.updateById(course);

        //添加市场信息
        courseMarketMapper.updateById(courseMarket);

        //添加课程详情
        courseDetailMapper.updateById(courseDetail);
        //3 进行百度内容自动审核
        auditHandle(ajaxResult.getMessage(),course);
    }

    @Override
    @Transactional
    public void insert(CourseDto courseDto) {
        Course course = courseDto.getCourse();
        CourseMarket courseMarket = courseDto.getCourseMarket();
        CourseDetail courseDetail = courseDto.getCourseDetail();
        //1 相关校验

        CourseGrade grade = CourseGrade.getGrade(course.getGradeId().intValue());
        ValidUtils.assertNotNull(grade, ErrorCode.CODE_400_COURSE_GRADE_ILLEGAL);

        String content = course.getName()+" "+ course.getForUser()+" "+ courseDetail.getIntro()+" "+ courseDetail.getDescription();
        AjaxResult ajaxResult = aiContentAuditService.audit(content, null, null);
        int status = ajaxResult.isSuccess() ? 1 : -1;
        //2 正在操作
        //添加课程
        course.setStatus(status);
        courseMapper.insert(course);

        //添加市场信息
        Long courseId = course.getId();
        courseMarket.setId(courseId);
        courseMarketMapper.insert(courseMarket);

        //添加课程详情
        courseDetail.setId(courseId);
        courseDetailMapper.insert(courseDetail);

        //3 进行百度内容自动审核
        auditHandle(ajaxResult.getMessage(),course);
    }

    @Override
    @Transactional
    public AjaxResult online(List<Long> ids) {
        // 1.空值校验
        ValidUtils.assertListNotNull(ids, ErrorCode.CODE_400_COURSE_LINE_ILLEGAL);
        // 2.修改状态
        courseMapper.online(ids);

        // 3.调用feign接口添加es
        List<CourseDoc> courseDocs = new ArrayList<>();
        List<CourseOnlineLog> courseOnlineLogs = new ArrayList<>();
        for (Long id : ids) {
            CourseDoc courseDoc = new CourseDoc();
            //处理course里面值
            Course course = courseMapper.selectById(id);
            BeanUtils.copyProperties(course,courseDoc);

            //处理课程类型
            Long courseTypeId = course.getCourseTypeId();
            CourseType courseType = courseTypeMapper.selectById(courseTypeId);
            courseDoc.setCourseTypeName(courseType.getName());
            //处理影响信息
            CourseMarket courseMarket = courseMarketMapper.selectById(id);
            BeanUtils.copyProperties(courseMarket,courseDoc);
            courseDocs.add(courseDoc);

            //处理上下线日志
            CourseOnlineLog log = course2OnlineLog(course);
            courseOnlineLogs.add(log);

        }

        // 4.保存上线日志
        /*List<CourseOnlineLog> courseOnlineLogs = ids.stream().map(id -> {
            Course course = courseMapper.selectById(id);
            CourseOnlineLog courseOnlineLog = new CourseOnlineLog();
            courseOnlineLog.setCourseId(course.getId());
            courseOnlineLog.setCourseName(course.getName());
            courseOnlineLog.setOnlineTime(new Date());
            courseOnlineLog.setState(1);
            return courseOnlineLog;
        }).collect(Collectors.toList());*/
        courseOnlineLogMapper.batchSave(courseOnlineLogs);
        courseDocClient.batchAdd(courseDocs);

        // 发送消息
        publishMessage(ids);
        return AjaxResult.me();
    }

    /**
     * 发送消息
     * @param ids
     */
    private void publishMessage(List<Long> ids) {
        // 短信
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.sms", ids);
        // 邮件
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.email", ids);
        // 站内信
        rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME_TOPIC, "message.system", ids);
    }

    /**
     * 将课程转换为上线日志
     * @param course
     * @return
     */
    private CourseOnlineLog course2OnlineLog(Course course) {
        UserContextInfo userContextInfo = UserContextInfoHolder
                .getUserContextInfo();
        CourseOnlineLog log = new CourseOnlineLog();
        log.setCourseId(course.getId());
        log.setCourseName(course.getName());
        log.setOprAdminId(userContextInfo.getEmployeeId());
        log.setOprAdminName(userContextInfo.getEmpUsername());
        log.setState(1);
        log.setOnlineTime(new Date());
        return log;
    }

    @Override
    @Transactional
    public AjaxResult offline(List<Long> ids) {
        // 1.空值校验
        ValidUtils.assertListNotNull(ids, ErrorCode.CODE_400_COURSE_LINE_ILLEGAL);
        // 2.修改状态
        courseMapper.offline(ids);

        // 3.调用feign接口添加es
        courseDocClient.batchDel(ids);
        // 4.保存下线日志
        List<CourseOnlineLog> courseOnlineLogs = ids.stream().map(id -> {
            Course course = courseMapper.selectById(id);
            CourseOnlineLog courseOnlineLog = new CourseOnlineLog();
            courseOnlineLog.setCourseId(course.getId());
            courseOnlineLog.setCourseName(course.getName());
            courseOnlineLog.setOnlineTime(new Date());
            courseOnlineLog.setState(2);
            return courseOnlineLog;
        }).collect(Collectors.toList());
        courseOnlineLogMapper.batchSave(courseOnlineLogs);

        return AjaxResult.me();
    }

    @Override
    public AjaxResult queryCourses(CourseDocQuery courseDocQuery) {
        return courseDocClient.queryCourse(courseDocQuery);
    }

    /**
     * 审核处理
     * @param message 处理信息
     * @param course 审核哪一个课程
     */
    private void auditHandle(String message,Course course) {
        CourseAuditLog auditLog = course2CourseAuditLog(course,message);
        courseAuditLogMapper.insert(auditLog);
    }

    /**
     * 保存课程审核日志
     * @param course 哪一个课程进行转化
     * @param message 信息
     * @return 课程审核日志
     */
    private CourseAuditLog course2CourseAuditLog(Course course, String message) {
        CourseAuditLog auditLog = new CourseAuditLog();
        auditLog.setCourseId(course.getId());
        auditLog.setCourseName(course.getName());
        auditLog.setState(course.getStatus());
        // 设置审核信息
        String note = course.getStatus()!=-1 ? "审核通过" : message;
        auditLog.setNote(note);
        auditLog.setAuditTime(new Date());
        auditLog.setAuditAdminId(null);
        auditLog.setAuditAdminName("系统自动审核");
        return auditLog;
    }

    @Override
    @Transactional
    public boolean deleteById(Serializable courseId) {

        //删除详情
        courseDetailMapper.deleteById(courseId);

        //删除营销信息
        courseMarketMapper.deleteById(courseId);

        //删除课程信息
        courseMapper.deleteById(courseId);

        //是否删除审核日志，上下架日志，看你的业务逻辑
        return  true;
    }
}
